<template>
  <div class="pan-department-management">
    <!-- 部门概览统计卡片区域 -->
    <el-card class="stats-card" :body-style="{ padding: '15px' }">
      <div class="stats-container">
        <StatisticCard
          label="总部门"
          :value="statistics.overview?.total_departments?.toString() || '0'"
          icon="el-icon-office-building"
          type="primary"
        />
        <StatisticCard
          label="活跃"
          :value="statistics.overview?.active_departments?.toString() || '0'"
          icon="el-icon-check"
          type="success"
        />
        <StatisticCard
          label="配置率"
          :value="
            statistics.overview?.configured_departments &&
            statistics.overview?.total_departments
              ? `${(
                  (statistics.overview.configured_departments /
                    statistics.overview.total_departments) *
                  100
                ).toFixed(2)}%`
              : '0%'
          "
          icon="el-icon-setting"
          type="info"
        />
        <StatisticCard
          label="总资产"
          :value="statistics.overview?.total_assets?.toString() || '0'"
          icon="el-icon-document"
          type="warning"
        />
        <StatisticCard
          label="分配率"
          :value="
            statistics.overview?.assignment_rate
              ? `${statistics.overview.assignment_rate.toFixed(2)}%`
              : '0%'
          "
          icon="el-icon-connection"
          type="primary"
        />
      </div>
    </el-card>
    <!-- 全局统计区域 -->
    <el-card class="global-stats-card" :body-style="{ padding: '15px' }">
      <h3 class="section-title">全局统计</h3>
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="stat-box">
            <h4 class="stat-box-title">资产分配</h4>
            <div class="stat-box-content">
              <div class="stat-item">
                <span class="stat-label">已分配:</span>
                <span class="stat-value success">
                  {{ statistics.overview?.assigned_assets || 0 }} ({{
                    statistics.overview?.total_assets
                      ? `${(
                          (statistics.overview.assigned_assets /
                            statistics.overview.total_assets) *
                          100
                        ).toFixed(0)}%`
                      : "0%"
                  }})
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-label">待分配:</span>
                <span class="stat-value warning">
                  {{ statistics.overview?.unassigned_assets || 0 }} ({{
                    statistics.overview?.total_assets
                      ? `${(
                          (statistics.overview.unassigned_assets /
                            statistics.overview.total_assets) *
                          100
                        ).toFixed(0)}%`
                      : "0%"
                  }})
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-label">总关键词:</span>
                <span class="stat-value">
                  {{ statistics.overview?.total_keywords || 0 }}个
                </span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-box">
            <h4 class="stat-box-title">责任人配置</h4>
            <div class="stat-box-content">
              <div class="stat-item">
                <span class="stat-label">已配置:</span>
                <span class="stat-value success">
                  {{ statistics.overview?.configured_departments || 0 }}/{{
                    statistics.overview?.total_departments || 0
                  }}
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-label">覆盖率:</span>
                <span class="stat-value">
                  {{
                    statistics.overview?.configured_departments &&
                    statistics.overview?.total_departments
                      ? `${(
                          (statistics.overview.configured_departments /
                            statistics.overview.total_departments) *
                          100
                        ).toFixed(2)}%`
                      : "0%"
                  }}
                </span>
              </div>
              <div class="stat-item">
                <span class="stat-label">负责人:</span>
                <span class="stat-value">
                  {{ getResponsiblePersonCount() }}人
                </span>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="8">
          <div class="stat-box">
            <h4 class="stat-box-title">告警信息</h4>
            <div class="stat-box-content">
              <div
                v-for="(alert, index) in statistics.alerts"
                :key="index"
                class="alert-item"
              >
                <el-tag
                  :type="getAlertType(alert.severity)"
                  size="small"
                  style="margin-right: 8px"
                >
                  {{ getAlertIcon(alert.severity) }}
                </el-tag>
                <span class="alert-message">{{ alert.message }}</span>
                <el-button
                  v-if="alert.departments && alert.departments.length > 0"
                  text
                  type="primary"
                  size="small"
                  @click="handleViewAlertDetail(alert)"
                >
                  详情
                </el-button>
              </div>
              <div v-if="!statistics.alerts || statistics.alerts.length === 0">
                <span class="no-alert">暂无告警信息</span>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        />
      </div>
    </el-card>

    <!-- 部门列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <div v-loading="loading" class="table-wrapper">
        <DynamicTable
          :data="departmentList"
          :columns="tableColumns"
          :loading="loading"
          :pagination="pagination"
          border
          row-key="id"
          selection-type="multiple"
          @selection-change="handleSelectionChange"
          @size-change="handleSizeChange"
          @current-page-change="handlePageChange"
        >
          <template #table-top>
            <div class="list-header">
              <div class="batch-actions">
                <el-button type="primary" @click="handleAdd">
                  新增部门
                </el-button>
                <el-button
                  type="success"
                  :disabled="selectedDepartments.length === 0"
                  @click="handleBatchAssign"
                >
                  批量分配资产
                </el-button>
                <el-button type="info" @click="handleExport">
                  导出数据
                </el-button>
                <el-button type="warning" @click="handleStatistics">
                  统计报表
                </el-button>
              </div>
              <div class="header-right">
                <span class="sort-label">排序:</span>
                <el-select
                  v-model="filterForm.sort_by"
                  size="small"
                  style="width: 140px; margin-right: 10px"
                  @change="handleSearch"
                >
                  <el-option label="按部门名称" value="department_name" />
                  <el-option label="按总资产" value="total_assets" />
                  <el-option label="按处理率" value="processing_rate" />
                  <el-option label="按创建时间" value="created_time" />
                </el-select>
                <el-select
                  v-model="filterForm.sort_order"
                  size="small"
                  style="width: 80px"
                  @change="handleSearch"
                >
                  <el-option label="升序" value="asc" />
                  <el-option label="降序" value="desc" />
                </el-select>
              </div>
            </div>
          </template>

          <template #responsible_person="{ row }">
            <div v-if="row.responsible_person" class="person-info">
              <div class="person-name">{{ row.responsible_person }}</div>
              <div v-if="row.responsible_email" class="person-detail">
                {{ row.responsible_email }}
              </div>
              <div v-if="row.responsible_phone" class="person-detail">
                {{ row.responsible_phone }}
              </div>
            </div>
            <span v-else class="no-data">-</span>
          </template>

          <template #backup_person="{ row }">
            <div v-if="row.backup_person" class="person-info">
              <div class="person-name">{{ row.backup_person }}</div>
              <div v-if="row.backup_email" class="person-detail">
                {{ row.backup_email }}
              </div>
              <div v-if="row.backup_phone" class="person-detail">
                {{ row.backup_phone }}
              </div>
            </div>
            <span v-else class="no-data">-</span>
          </template>

          <template #total_assets="{ row }">
            <span class="asset-count">{{
              row.statistics?.total_assets || 0
            }}</span>
          </template>

          <template #is_configured="{ row }">
            <el-tag
              :type="row.is_configured ? 'success' : 'warning'"
              size="small"
            >
              {{ row.is_configured ? "✅" : "⚠️" }}
            </el-tag>
          </template>

          <template #action="{ row }">
            <el-button
              size="small"
              type="primary"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button size="small" type="warning" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </DynamicTable>
      </div>
    </el-card>

    <!-- 部门详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :department-detail="departmentDetail"
      :loading="detailLoading"
    />

    <!-- 部门表单弹窗 -->
    <FormModal
      v-model="formVisible"
      :department-detail="formDepartmentDetail"
      :is-edit="isEditMode"
      :responsible-person-options="responsiblePersonOptions"
      @save="handleFormSave"
    />

    <!-- 批量分配资产弹窗 -->
    <BatchAssignModal
      v-model="batchAssignVisible"
      :selected-departments="selectedDepartments"
      @success="handleBatchAssignSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import StatisticCard from "./components/StatisticCard.vue";
import {
  getPanDepartments,
  getPanDepartmentDetail,
  deletePanDepartment,
  createPanDepartment,
  updatePanDepartment,
  getPanDepartmentStatistics,
  getPanResponsiblePersons,
} from "../../servers";
import DetailModal from "./components/DetailModal.vue";
import FormModal from "./components/FormModal.vue";
import BatchAssignModal from "./components/BatchAssignModal.vue";

// 页面状态
const loading = ref(false);
const detailVisible = ref(false);
const currentDepartmentId = ref<number | null>(null);
const departmentDetail = ref<any>(null);
const detailLoading = ref(false);

// 表单弹窗状态
const formVisible = ref(false);
const formDepartmentDetail = ref<any>(null);
const isEditMode = ref(false);

// 批量分配弹窗状态
const batchAssignVisible = ref(false);

// 统计数据
const statistics = reactive<any>({
  overview: null,
  alerts: [],
});

// 部门列表数据
const departmentList = ref<any[]>([]);

// 选中的部门
const selectedDepartments = ref<any[]>([]);

// 责任人列表
const responsiblePersonOptions = ref<
  Array<{
    name: string;
    email?: string;
    phone?: string;
    title?: string;
  }>
>([]);

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  department_name: "",
  status: "",
  responsible_person: "",
  sort_by: "department_name",
  sort_order: "asc",
});

// 筛选表单配置
const filterFormConfig = computed(() => {
  return [
    {
      key: "department_name",
      name: "部门名称",
      type: "input",
      placeholder: "请输入部门名称",
      col: { span: 6 },
    },
    {
      key: "status",
      name: "状态",
      type: "select",
      placeholder: "全部",
      params: { clearable: true },
      options: [
        { label: "全部", value: "" },
        { label: "活跃", value: "active" },
        { label: "非活跃", value: "inactive" },
        { label: "已归档", value: "archived" },
      ],
      col: { span: 6 },
    },
    {
      key: "responsible_person",
      name: "责任人",
      type: "input",
      placeholder: "请输入责任人姓名",
      col: { span: 6 },
    },
  ] as FormItemConfig[];
});

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "部门代码",
    prop: "department_code",
    minWidth: 120,
    fixed: "left",
  },
  {
    label: "部门名称",
    prop: "department_name",
    minWidth: 150,
  },
  {
    label: "主责任人",
    prop: "responsible_person",
    minWidth: 200,
    slot: "responsible_person",
  },
  {
    label: "备用责任人",
    prop: "backup_person",
    minWidth: 200,
    slot: "backup_person",
  },
  {
    label: "总资产",
    prop: "total_assets",
    width: 100,
    align: "center",
    slot: "total_assets",
  },
  {
    label: "配置",
    prop: "is_configured",
    width: 100,
    align: "center",
    slot: "is_configured",
  },
  {
    label: "操作",
    width: 250,
    fixed: "right",
    slot: "action",
  },
];

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
});

// 获取责任人列表
const fetchResponsiblePersons = async () => {
  try {
    const result = await getPanResponsiblePersons({
      group_by: "person",
    });

    if (result.code === 200 && result.data) {
      // 兼容不同的数据结构
      const personList =
        result.data.responsible_persons || result.data.by_person || [];

      const persons = personList.map((item: any) => {
        // 尝试从不同位置获取部门信息
        const primaryDept = item.primary_departments?.[0] || {};

        // 提取责任人信息，优先使用 primary_departments 中的数据
        return {
          name: item.person_name || item.name,
          email: primaryDept?.email || item.email || undefined,
          phone: primaryDept?.phone || item.phone || undefined,
          title: primaryDept?.title || item.title || undefined,
        };
      });
      responsiblePersonOptions.value = persons;
      console.log("责任人列表加载完成:", persons);
    }
  } catch (error) {
    console.error("获取责任人列表失败:", error);
  }
};

// 获取部门统计
const fetchDepartmentStatistics = async () => {
  try {
    const result = await getPanDepartmentStatistics({
      time_range: "all",
    });

    statistics.overview = result.data.overview || null;
    statistics.alerts = result.data.alerts || [];

    // 合并统计数据到部门列表
    if (result.data.department_details && departmentList.value.length > 0) {
      const detailsMap = new Map(
        result.data.department_details.map((dept: any) => [
          dept.department_id,
          dept,
        ])
      );

      departmentList.value.forEach((dept) => {
        const detail = detailsMap.get(dept.id) as any;
        if (detail) {
          // 合并统计数据
          dept.statistics = {
            total_assets: detail.total_assets || 0,
            ai_inference_count: detail.ai_inference_count || 0,
            manual_confirm_count: detail.manual_confirm_count || 0,
          };
        }
      });
    }
  } catch (error: any) {
    console.error("获取部门统计失败:", error);
  }
};

// 获取部门列表
const fetchDepartmentList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      per_page: pagination.pageSize,
      sort_by: filterForm.sort_by,
      sort_order: filterForm.sort_order,
    };

    // 处理筛选参数
    if (filterForm.department_name) {
      params.department_name = filterForm.department_name;
    }
    if (filterForm.status) {
      params.status = filterForm.status;
    }
    if (filterForm.responsible_person) {
      params.responsible_person = filterForm.responsible_person;
    }

    const result = await getPanDepartments(params);

    departmentList.value = result.data.departments || [];

    // 更新分页信息
    if (result.data.pagination) {
      pagination.total = result.data.pagination.total || 0;
      pagination.currentPage = result.data.pagination.page || 1;
      pagination.pageSize = result.data.pagination.per_page || 20;
    }

    // 获取统计并合并数据
    await fetchDepartmentStatistics();
  } catch (error: any) {
    ElMessage.error(error?.message || "获取部门列表失败");
  } finally {
    loading.value = false;
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.department_name = "";
  filterForm.status = "";
  filterForm.responsible_person = "";
  filterForm.sort_by = "department_name";
  filterForm.sort_order = "asc";
  pagination.currentPage = 1;
  fetchDepartmentList();
};

const handleSearch = (values: any) => {
  pagination.currentPage = 1;
  fetchDepartmentList();
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchDepartmentList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchDepartmentList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedDepartments.value = selection;
};

// 获取责任人数量
const getResponsiblePersonCount = (): number => {
  const persons = new Set<string>();
  departmentList.value.forEach((dept) => {
    if (dept.responsible_person) {
      persons.add(dept.responsible_person);
    }
    if (dept.backup_person) {
      persons.add(dept.backup_person);
    }
  });
  return persons.size;
};

// 获取告警类型
const getAlertType = (
  severity?: string
): "success" | "warning" | "danger" | "info" => {
  const typeMap: Record<string, "success" | "warning" | "danger" | "info"> = {
    error: "danger",
    warning: "warning",
    info: "info",
  };
  return typeMap[severity || ""] || "info";
};

// 获取告警图标
const getAlertIcon = (severity?: string): string => {
  const iconMap: Record<string, string> = {
    error: "❌",
    warning: "⚠️",
    info: "📊",
  };
  return iconMap[severity || ""] || "ℹ️";
};

// 查看详情
const handleViewDetail = async (row: any) => {
  const departmentId = row.id;
  if (!departmentId) {
    ElMessage.warning("部门ID不存在");
    return;
  }

  currentDepartmentId.value = departmentId;
  detailVisible.value = true;
  await fetchDepartmentDetail(departmentId);
};

// 获取部门详情
const fetchDepartmentDetail = async (departmentId: number) => {
  detailLoading.value = true;
  try {
    const result = await getPanDepartmentDetail(departmentId);

    departmentDetail.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取部门详情失败");
    departmentDetail.value = null;
  } finally {
    detailLoading.value = false;
  }
};

// 新增部门
const handleAdd = () => {
  isEditMode.value = false;
  formDepartmentDetail.value = null;
  formVisible.value = true;
};

// 编辑部门
const handleEdit = async (row: any) => {
  const departmentId = row.id;
  if (!departmentId) {
    ElMessage.warning("部门ID不存在");
    return;
  }

  isEditMode.value = true;
  formVisible.value = true;

  // 获取部门详情用于编辑
  try {
    const result = await getPanDepartmentDetail(departmentId);

    formDepartmentDetail.value = result.data;
  } catch (error: any) {
    ElMessage.error(error?.message || "获取部门详情失败");
    formVisible.value = false;
  }
};

// 删除部门
const handleDelete = async (row: any) => {
  const departmentId = row.id;
  if (!departmentId) {
    ElMessage.warning("部门ID不存在");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除部门【${row.department_name}】吗？此操作不可恢复！`,
      "删除确认",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;
    await deletePanDepartment(departmentId);

    ElMessage.success("部门删除成功");
    fetchDepartmentList();
    fetchDepartmentStatistics(); // 刷新统计
  } catch (error: any) {
    if (error !== "cancel") {
      ElMessage.error(error?.message || "操作失败");
    }
  } finally {
    loading.value = false;
  }
};

// 保存表单（新增或编辑）
const handleFormSave = async (data: any) => {
  try {
    loading.value = true;

    if (isEditMode.value && formDepartmentDetail.value) {
      // 编辑模式
      const departmentId = formDepartmentDetail.value.id;
      const result = await updatePanDepartment(departmentId, data);

      ElMessage.success("部门更新成功");
      formVisible.value = false;
      fetchDepartmentList();
      fetchDepartmentStatistics(); // 刷新统计
    } else {
      // 新增模式
      const result = await createPanDepartment(data);

      ElMessage.success("部门创建成功");
      formVisible.value = false;
      fetchDepartmentList();
      fetchDepartmentStatistics(); // 刷新统计
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "操作失败");
  } finally {
    loading.value = false;
  }
};

// 批量分配资产
const handleBatchAssign = () => {
  if (selectedDepartments.value.length === 0) {
    ElMessage.warning("请先选择要分配资产的部门");
    return;
  }
  batchAssignVisible.value = true;
};

// 批量分配成功回调
const handleBatchAssignSuccess = () => {
  // 刷新列表和统计
  fetchDepartmentList();
  fetchDepartmentStatistics();
};

// 导出数据
const handleExport = () => {
  ElMessage.info("导出数据功能待实现");
};

// 统计报表
const handleStatistics = () => {
  ElMessage.info("统计报表功能待实现");
};

// 查看告警详情
const handleViewAlertDetail = (alert: any) => {
  if (alert.departments && alert.departments.length > 0) {
    ElMessageBox.alert(
      `未配置的部门：${alert.departments.join("、")}`,
      "告警详情",
      {
        confirmButtonText: "确定",
      }
    );
  }
};

// 初始化
onMounted(() => {
  fetchResponsiblePersons(); // 先获取责任人列表
  fetchDepartmentList(); // fetchDepartmentList 内部会调用 fetchDepartmentStatistics
});
</script>

<style scoped lang="scss">
.pan-department-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .stats-card,
  .filter-card,
  .table-card,
  .global-stats-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .stats-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .filter-content {
    padding: 5px 0;
  }

  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;

    .batch-actions {
      display: flex;
      gap: 10px;
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 10px;

      .sort-label {
        color: #606266;
        font-size: 14px;
      }
    }
  }

  .table-wrapper {
    min-height: 200px;
  }

  .person-info {
    .person-name {
      font-weight: 500;
      color: #303133;
      margin-bottom: 4px;
    }

    .person-detail {
      font-size: 12px;
      color: #909399;
      line-height: 1.5;
    }
  }

  .asset-count {
    font-weight: 600;
    color: #409eff;
    font-size: 16px;
  }

  .no-data {
    color: #909399;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #303133;
  }

  .stat-box {
    background-color: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    padding: 15px;
    height: 100%;

    .stat-box-title {
      font-size: 14px;
      font-weight: 500;
      margin: 0 0 12px 0;
      color: #303133;
      border-bottom: 1px solid #e4e7ed;
      padding-bottom: 8px;
    }

    .stat-box-content {
      .stat-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        &:last-child {
          margin-bottom: 0;
        }

        .stat-label {
          color: #606266;
          font-size: 13px;
        }

        .stat-value {
          font-weight: 600;
          font-size: 14px;

          &.success {
            color: #67c23a;
          }

          &.warning {
            color: #e6a23c;
          }
        }
      }

      .alert-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        padding: 6px;
        background-color: #f5f7fa;
        border-radius: 4px;

        &:last-child {
          margin-bottom: 0;
        }

        .alert-message {
          flex: 1;
          font-size: 13px;
          color: #606266;
        }
      }

      .no-alert {
        color: #909399;
        font-size: 13px;
      }
    }
  }
}
</style>
